package com.woniuxy.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 大概底层实现的加锁 不要用户开发
 *
 * <P> Date: 2022/4/9:18:19
 * <P> Description:
 */
@Slf4j(topic = "c.LockCas")
@SuppressWarnings("all")
public class LockCas extends Thread {

    /**
     * TODO 0 表示无锁   1  表示上锁
     */
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        System.out.println("unlock");
        state.set(0);
    }

    public static void main(String[] args) {
        LockCas lock = new LockCas();

        new Thread(() -> {
            log.debug("begin");
            lock.lock();
            try {
                log.debug("lock...");
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();


        new Thread(() -> {
            log.debug("begin");
            lock.lock();
            try {
                log.debug("lock...");
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();


    }
}
